package com.zhl.dao.impl;

import com.zhl.dao.UserDao;
import com.zhl.entity.User;
import com.zhl.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao {
    private QueryRunner queryRunner;
    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }
    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

    @Override
    public List<User> findAllUser() {

        try {
            return queryRunner.query(connectionUtils.getConnection(),"select * from user",new BeanListHandler<User>(User.class));
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public User findOne(Integer id) {

        try {
            return queryRunner.query(connectionUtils.getConnection(),"select * from user where id = ?",new BeanHandler<User>(User.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void addUser(User user) {
        try {
            queryRunner.update(connectionUtils.getConnection(),"insert into user(username,password,money) values(?,?,?)",user.getUsername(),user.getPassword(),user.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteUser(Integer id) {
        try {
            queryRunner.update( connectionUtils.getConnection(),"delete from user where id = ?",id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateUser(User user) {
        try {
            queryRunner.update(connectionUtils.getConnection(),"update user set username=?,password=?,money=? where id=?",user.getUsername(),user.getPassword(),user.getMoney(),user.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public User findUserByName(String userName) {
        try {
            List<User> users = queryRunner.query(connectionUtils.getConnection(),"select * from user where username=?",
                    new BeanListHandler<User>(User.class), userName);
            if(users.size()==0 || users == null){
                return null;
            }
            if (users.size()>1){
                throw  new RuntimeException("当前结果不是唯一的");
            }
            return  users.get(0);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
}
